$(function(){

    $("#addPlayer").click(function(){

        modalWindowHandler.setWindowPosition('top');
        modalWindowHandler.setModalWindowTitle("Add Player");
        modalWindowHandler.setContent('getAddPlayerForm');

        //modalWindowHandler.AJAXCallbackFunction = ("setUpAddTeamModalWindow");
        modalWindowHandler.openModalWindow();
        //setUpAddPlayerModalWindow();
        modalWindowHandler.setWindowWidth('400')
        sendRequest.setAction('getAddPlayerForm');
        sendRequest.setSendParameters({});
        $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
        {
            $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
            $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
            $("#mask").empty();
            $(".errorMessageDiv").hide();
            // modalWindowHandler.openModalWindow();
            setUpAddPlayerModalWindow();
        });


    });


    $('.viewPlayerDetails').click(function(){
        var playerID = $(this).attr('name');
        postData = {
            "playerID":playerID
        };
        modalWindowHandler.setWindowPosition('center');
        modalWindowHandler.setModalWindowTitle("View Player Details");
        modalWindowHandler.setWindowWidth('550');
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        //modalWindowHandler.openModalWindow();
        $( "#modalDialogWindow" ).dialog('open');
        sendRequest.setAction('viewPlayerDetails');
        sendRequest.setSendParameters(postData);
        //
        $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
        {
            $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
            $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
            $("#mask").empty();
            $(".errorMessageDiv").hide();
            setUpPlayerDetailsModalWindow();
        });

    });


    $("#deletePlayers").click(function(){
        modalWindowHandler.setWindowPosition('top');
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#modalDialogWindow" ).dialog('open');
        modalWindowHandler.setModalWindowTitle("Delete Cricket Player");
        modalWindowHandler.setContent('getDeletePlayerForm');
        modalWindowHandler.setWindowWidth('650')
        sendRequest.setAction('getDeletePlayerForm');
        sendRequest.setSendParameters({});
        $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
        {
            $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
            $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
            $("#mask").empty();
            $(".errorMessageDiv").hide();
            // modalWindowHandler.openModalWindow();
            setUpPlayerDeleteModalWindow();

        });
    });
});




$.widget( "custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function( ul, items ) {
        var self = this,
        currentCategory = "";
        $.each( items, function( index, item ) {
            if ( item.category != currentCategory ) {
                ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                currentCategory = item.category;
            }
            self._renderItem( ul, item );
        });
    }
});

function deletePlayerListisSelected()
{
    //         $(".selectableDeletePlayerClass").each( function() {
    //    $( ".errorMessageDiv" ).append($(this).text());
    if ($('.ui-widget-content').hasClass('ui-selected')) {
               
        //#elm has the class

        return true;
    } else {
        //#elm doesn't have the class
        return false;
    }
//               });
//  return false;
}
function setUpPlayerDeleteModalWindow()
{
    $( ".errorMessageDiv" ).show();
    $( ".selectableDeletePlayerClass" ).selectable({
        stop: function() {
            //var result = $( ".errorMessageDiv" );
            $( ".ui-selected", this ).each(function() {
                var index = $( ".selectableDeletePlayerClass li" ).index( this );
                var playerName = $(this).text();
                //result.append( " #" + ( playerName + 1 ) );
                $(".selectableDeletePlayerClass .ui-selected").each( function() {

                    if($(this).text() != playerName) {

                        $('.selectableDeletePlayerClass .ui-selected').removeClass('ui-selected');
                    }
                });
            });


        }
    });

    $("#modalDialogWindow").dialog( "option", "buttons", {

        "Delete Player": function() {
            $( ".errorMessageDiv" ).hide();
            if (deletePlayerListisSelected())
            {
                $(".ui-dialog-buttonpane button:contains('Delete Player')").unbind();
                $( "#modalDialogWindow" ).children("#modalWindowContent").append('<div id="deleteConfirmation"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>The selected player will be permanently deleted and cannot be recovered. Additionally, all statistics for this player will be deleted as well. Are you sure you want delete this player?</p></div>');
                $("#deleteConfirmation").hide();
                $( ".errorMessageDiv" ).hide();
                $('#deletePlayerListContainer').fadeOut();
                $("#deleteConfirmation").delay(1100).fadeIn('slow');
                $( "#modalDialogWindow" ).dialog( "option", "title", 'Confirm Player Delete');
                $(".ui-dialog-buttonpane button:contains('Delete Player')").click(function(){
                    //$( "#modalDialogWindow" ).dialog('close');
                    var playerID = $('.ui-widget-content .ui-selected').attr('name');
                    var playerName = $('.ui-widget-content .ui-selected').text();
                    var teamData = {
                        "playerName": playerName,
                        "playerID":playerID
                    };
                    sendRequest.setAction('deletePlayer');
                    sendRequest.setSendParameters(teamData);

                    $(".errorMessageDiv").load(sendRequest.serverURL,sendRequest.getSendData(),function (response)
                    {
                        var deleteSuccess = ($('.errorMessageDiv').html()).replace(/^\s*|\s*$/g,'');
                        if (deleteSuccess == '1')
                        {
                            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
                            $( "#modalDialogWindow" ).dialog( "option", "title", 'Delete Successful');
                            $(".ui-dialog-buttonpane button:contains('Delete Player')").children('span').text('OK');
                            $( "#modalDialogWindow" ).children("#modalWindowContent").html('<div id="deleteConfirmation"><p><span class="ui-icon ui-icon-check" style="float:left; margin:0 7px 20px 0;"></span>The selected player has been deleted successfully. All statistics belonging to this player have been succcessfully deleted as well.</p></div>');
                            $( "#modalDialogWindow" ).children("#modalWindowContent").show('bounce',{},500);
                            updateTeamList();
                            $(".ui-dialog-buttonpane button:contains('OK')").click(function(){
                                $( "#modalDialogWindow" ).dialog('close');
                            });
                        }
                        else
                        {
                            formValidator.updateErrorMessage("Delete of player has failed. Please contact your software administrator.");

                        }
                    });


                });
            }
            else
            {
                formValidator.updateErrorMessage("No player has been selected for deletion. Please select a single player from the lists to delete.");
            }
        // jQuery(this).dialog('close');
        //  jQuery('.errorMessageDiv').html('');
        },
        "Close": function() {
            jQuery(this).dialog('close');
            jQuery('.errorMessageDiv').html('');
        }

    });
}
function setUpPlayerDetailsModalWindow()
{
    $("#modalDialogWindow").dialog( "option", "buttons", {
        
        "OK": function() {
            jQuery(this).dialog('close');
            jQuery('.errorMessageDiv').html('');
        }

    });
}
function setUpAddPlayerModalWindow()
{
    $("#bowlingTypeContainer").hide();
    $( "#dob" ).datepicker();
    $( "#dob" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
    $( "#slider-range-height" ).slider({
        range: "min",
        step: 0.01,
        value: 1.50,
        min: 0.50,
        max: 3.00,
        slide: function( event, ui ) {
            $( "#height" ).val( ui.value+" meters" );
            $( "#height-feet" ).val( Math.round((parseFloat(ui.value*3.2808399)*100))/100+" feet" );
                                
        }
    });
    $( "#height" ).val( $( "#slider-range-height" ).slider( "value" ) + " meters" );
    $( "#height-feet" ).val( Math.round(parseFloat($( "#slider-range-height" ).slider( "value" )*3.2808399)*100)/100 + " feet" );

    var availableFeildingPositions = [
    "Third Man",
    "Long Stop",
    "Fine Leg",
    "Long Leg",
    "Deep Backward Square Leg",
    "Deep Square Leg",
    "Deep Mid-wicket",
    "Cow Corner",
    "Long On",
    "Long Off",
    "Deep Extra Cover",
    "Deep Cover",
    "Sweeper",
    "Backward Point",
    "Fly Slip",
    "Short Fine Leg",
    "Short Backward Square Leg",
    "Mid-Wicker",
    "Mid-On",
    "Short Leg",
    "Leg Slip",
    "Silly Mid-On",
    "Extra Cover",
    "Cover",
    "Cover Point",
    "Point",
    "Mid-Off",
    "Short Mid-Off",
    "Silly Mid-Off",
    "Silly Point",
    "Gully",
    "Wicket keeper",
    "First Slip",
    "Second Slip",
    "Third Slip",
    "Fourth Slip"
    ];
    $( "#fieldingPosition" ).autocomplete({
        source: availableFeildingPositions
    });
    $('#container_batsmanType').buttonset();
    $( "#isBowlerSelector" ).button();

    $( "#isBatsmanSelector" ).button();
                
    $("#isBowlerSelector").change(function(){
                
        if ($('#isBowlerSelector').is(':checked'))
        {
            $("#bowlingTypeContainer").slideDown('slow');
        }
        else
        {
            $("#bowlingTypeContainer").slideUp('slow');
            jQuery(':input[id=bowlingType]').val('');
        }

    });

    var availableBowlingTypes = [
    {
        label: "Seam Bowling",
        category: "Fast Bowling"
    },

    {
        label: "Swing Bowling",
        category: "Fast Bowling"
    },

    {
        label: "Medium Pace Bowling",
        category: ""
    },

    {
        label: "Off-Spin (Finger Spin)",
        category: "Spin Bowling"
    },

    {
        label: "Off-Spin",
        category: "Finger Spin"
    },

    {
        label: "Left-Arm Orthodox",
        category: "Finger Spin"
    },

    {
        label: "Left-Arm Orthodox (Finger Spin)",
        category: "Finger Spin"
    },

    {
        label: "Leg Spin (Wrist Spin)",
        category: "Spin Bowling"
    },

    {
        label: "Leg Spin",
        category: "Wrist Spin"
    },

    {
        label: "Throwing",
        category: ""
    }
    ];

    jQuery(':input[id=bowlingType]').catcomplete({
        delay: 0,
        source: availableBowlingTypes
    });

    $("#modalDialogWindow").dialog( "option", "buttons", {
        "Add Player": function() {

            var firstName = jQuery(':input[id=firstName]');
            var lastName = jQuery(':input[id=lastName]');
            var teamNameID = jQuery('#teamNameDD');
            var dob = jQuery(':input[id=dob]');
            var nickName = jQuery(':input[id=nickName]');
            var height = jQuery(':input[id=height]');
            var playerProfile = jQuery(':input[id=playerProfile]');
            var fieldingPosition = jQuery(':input[id=fieldingPosition]');
            var batsmanType = $("input:radio[name=batsmanType]:checked");
            var bowlingType = jQuery(':input[id=bowlingType]');
            var pob = jQuery(':input[id=pob]');







            var allFields = jQuery([]).add(firstName).add(lastName).add(teamNameID).add(dob).add(nickName).add(height).add(playerProfile).add(fieldingPosition).add(batsmanType).add(bowlingType).add(pob);
            var bValid = true;
            allFields.removeClass('ui-state-error');

            bValid = bValid && formValidator.checkLength(firstName,"the cricket player's first name",3,100);
            bValid = bValid && formValidator.checkRegexp(firstName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The cricket player's first name field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(lastName,"the cricket player's last name",3,100);
            bValid = bValid && formValidator.checkRegexp(teamNameID,/^[1234567890\s]*$/,"The cricket player's team name field only allows a numeric team ID (0-9).");
            bValid = bValid && formValidator.checkLength(teamNameID,"the cricket player's team name",1,2);
            // bValid = bValid && formValidator.checkRegexp(lastName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The cricket player's last name field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(pob,"the cricket player's place of birth",3,100);
            bValid = bValid && formValidator.checkRegexp(pob,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The cricket player's place of birth only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkRegexp(dob,/(\d{4})-(\d{2})-(\d{2})/,"The cricket player's date of birth is invalid. The format of the date required is yyyy-mm-dd.");

            bValid = bValid && formValidator.checkLength(nickName,"the cricket player's nick name",3,100);
            bValid = bValid && formValidator.checkRegexp(nickName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The cricket player's nick name field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(height,"the cricket player's height",3,15);
            bValid = bValid && formValidator.checkRegexp(height,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s\.]*$/,"The cricket player's height field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(playerProfile,"the cricket player's profile",10,250);
            bValid = bValid && formValidator.checkRegexp(playerProfile,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s\.]*$/,"The cricket player's profile field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(fieldingPosition,"the cricket player's fielding position",4,50);
            bValid = bValid && formValidator.checkRegexp(fieldingPosition,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s\-\.]*$/,"The cricket player's feilding position field only allows alphanumeric characters (a-z 0-9).");
            bValid = bValid && formValidator.checkLength(batsmanType,"the cricket player's batting type",1,10);
            bValid = bValid && formValidator.checkRegexp(batsmanType,/^([0-9a-zA-Z])+$/,"The cricket player's batting type field only allows alphanumeric characters (a-z 0-9).");
            if ($('#isBowlerSelector').is(':checked'))
            {
                bValid = bValid && formValidator.checkLength(bowlingType,"the cricket player's bowling action type",4,50);
                bValid = bValid && formValidator.checkRegexp(bowlingType,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(\)\s\-\.]*$/,"The ccricket player's bowling action type only allows alphanumeric characters (a-z 0-9).");
            }
            if (bValid) {


                var hiddenResponseDiv = jQuery('.responseDiv');
                hiddenResponseDiv.hide();
                var isSpecialistBatsman =null
                if ($('#isBatsmanSelector').is(':checked'))
                {
                    isSpecialistBatsman = true;
                }
                else
                {
                    isSpecialistBatsman = false;
                }

                sendRequest.setAction('insertNewPlayer');
                if ($('#isBowlerSelector').is(':checked'))
                {
                    formData = {
                        'firstName':firstName.val(),
                        'lastName':lastName.val(),
                        'teamNameID':teamNameID.val(),
                        'pob':pob.val(),
                        'dob':dob.val(),
                        'nickName':nickName.val(),
                        'height':height.val(),
                        'playerProfile':playerProfile.val(),
                        'fieldingPosition':fieldingPosition.val(),
                        'batsmanType':batsmanType.val(),
                        'bowlingType':bowlingType.val(),
                        'isSpecialistBatsman':isSpecialistBatsman
                    }    
                }
                else
                {
                    formData = {
                        'firstName':firstName.val(),
                        'lastName':lastName.val(),
                        'teamNameID':teamNameID.val(),
                        'pob':pob.val(),
                        'dob':dob.val(),
                        'nickName':nickName.val(),
                        'height':height.val(),
                        'playerProfile':playerProfile.val(),
                        'fieldingPosition':fieldingPosition.val(),
                        'batsmanType':batsmanType.val(),
                        'bowlingType':"Not a Bowler",
                        'isSpecialistBatsman':isSpecialistBatsman
                    }
                }

                sendRequest.setSendParameters(formData);

                hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                    hiddenResponseDiv.unbind();
                    var registrationResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                    // hiddenResponseDiv.html(registrationResponse).show();
                    hiddenResponseDiv.unbind();
                    if (formValidator.hasNumbers(registrationResponse))
                    {
                        $("#modalDialogWindow").dialog('close');
                        jQuery('.errorMessageDiv').html('');
                        updateTeamList();
                    }
                    else
                    {
                        firstName.addClass('ui-state-error');
                        LastName.addClass('ui-state-error');
                        formValidator.updateErrorMessage("Player Name Already Exists. Please insert a new Player Name");
                    }
                });
            }
        },
        "Cancel": function() {
            jQuery(this).dialog('close');
            jQuery('.errorMessageDiv').html('');
        }

    });
}


function updateTeamList()
{
    sendRequest.setAction('updatePlayerList');

    sendRequest.setSendParameters({});
    $('#mask').load(sendRequest.serverURL, sendRequest.getSendData(), function(){
        $( "#playerListContainer" ).html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#playerListContainer" ).hide();
        $( "#playerListContainer" ).delay(500).html($("#mask").html()).fadeIn('slow');
        $("#mask").empty();
        $("#tablesorter-playerlist").tablesorter({
            sortList:[[0,0],[2,1]],
            widgets: ['zebra']
            });
        $("#options").tablesorter({
            sortList: [[0,0]],
            headers: {
                3:{
                    sorter: true
                },
                4:{
                    sorter: false
                }
            }
        });
    $('.viewPlayerDetails').click(function(){
        var playerID = $(this).attr('name');
        postData = {
            "playerID":playerID
        };
        modalWindowHandler.setWindowPosition('center');
        modalWindowHandler.setModalWindowTitle("View Player Details");
        modalWindowHandler.setWindowWidth('550');
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        //modalWindowHandler.openModalWindow();
        $( "#modalDialogWindow" ).dialog('open');
        sendRequest.setAction('viewPlayerDetails');
        sendRequest.setSendParameters(postData);
        //
        $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
        {
            $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
            $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
            $("#mask").empty();
            $(".errorMessageDiv").hide();

            setUpPlayerDetailsModalWindow();
        });

    });
});


}

